// Mock数据服务
// 用于模拟后端接口响应，方便前端开发和测试

import { ElMessage } from 'element-plus'

// 模拟延迟
const delay = (ms = 500) => new Promise(resolve => setTimeout(resolve, ms))

// 模拟成功响应
const mockSuccess = (data, msg = 'success') => {
  return {
    code: 0,
    msg,
    data
  }
}

// 模拟错误响应
const mockError = (code, msg) => {
  return {
    code,
    msg
  }
}

// 模拟网络错误
const mockNetworkError = () => {
  throw new Error('网络连接失败')
}

// 随机生成数据
const random = {
  // 随机数
  number: (min, max) => Math.floor(Math.random() * (max - min + 1)) + min,

  // 随机浮点数
  float: (min, max, decimals = 2) => {
    const num = Math.random() * (max - min) + min
    return parseFloat(num.toFixed(decimals))
  },

  // 随机选择数组中的元素
  choice: (arr) => arr[Math.floor(Math.random() * arr.length)],

  // 随机日期
  date: (start = new Date(2023, 0, 1), end = new Date()) => {
    return new Date(start.getTime() + Math.random() * (end.getTime() - start.getTime()))
  },

  // 随机手机号
  phone: () => {
    const prefixes = ['130', '131', '132', '133', '134', '135', '136', '137', '138', '139']
    const prefix = random.choice(prefixes)
    const suffix = Math.random().toString().slice(2, 11)
    return prefix + suffix
  }
}

// 认证相关Mock数据
export const authMock = {
  // 发送验证码
  sendCode: async (phoneNumber) => {
    await delay(1000)

    // 模拟手机号格式验证
    if (!/^1[3-9]\d{9}$/.test(phoneNumber)) {
      throw mockError(40001, '手机号码格式有误')
    }

    // 模拟发送频率限制
    if (Math.random() < 0.1) {
      throw mockError(42901, '同一手机号 60 秒内只能发送一次验证码')
    }

    return mockSuccess(null, '验证码已发送')
  },

  // 用户注册
  register: async (data) => {
    await delay(1500)

    // 模拟各种验证错误
    if (data.password.length < 6 || data.password.length > 20) {
      throw mockError(40004, '密码长度需为 6 - 20 位')
    }

    if (data.password !== data.confirmPassword) {
      throw mockError(40005, '两次输入的密码不一致')
    }

    if (data.username.length < 3 || data.username.length > 20) {
      throw mockError(40006, '用户名可包含字母、数字、下划线，长度为 3 - 20 位')
    }

    if (data.verificationCode !== '123456') {
      throw mockError(40002, '验证码错误')
    }

    // 模拟用户名冲突
    if (data.username === 'admin') {
      throw mockError(40902, '用户名已被占用')
    }

    return mockSuccess({
      userId: random.number(10000, 99999),
      username: data.username,
      phoneNumber: data.phoneNumber,
      createdAt: new Date().toISOString()
    })
  },

  // 用户登录
  login: async (data) => {
    await delay(1000)

    // 模拟用户不存在
    if (data.username === 'nonexistent') {
      throw mockError(40401, '用户不存在')
    }

    // 模拟密码错误
    if (data.password !== 'admin') {
      throw mockError(40101, '密码错误')
    }

    return mockSuccess({
      userId: random.number(10000, 99999),
      username: data.username,
      lastLogin: new Date().toISOString(),
      token: 'mock-jwt-token-' + Date.now()
    })
  },

  // 重置密码
  resetPassword: async (data) => {
    await delay(1500)

    if (data.verificationCode !== '654321') {
      throw mockError(40003, '验证码已过期')
    }

    if (data.newPassword.length < 6 || data.newPassword.length > 20) {
      throw mockError(40007, '新密码长度需为 6 - 20 位')
    }

    if (data.newPassword !== data.confirmPassword) {
      throw mockError(40008, '两次输入的新密码不一致')
    }

    return mockSuccess(null, '密码已重置')
  }
}

// 监控相关Mock数据
export const monitorMock = {
  // 上传环境数据
  uploadEnvironmentData: async (data) => {
    await delay(800)

    // 模拟数据验证
    if (data.dissolvedOxygen < 0 || data.dissolvedOxygen > 20) {
      throw mockError(400, '溶解氧数值异常')
    }

    if (data.waterTemperature < -10 || data.waterTemperature > 50) {
      throw mockError(400, '水温数值异常')
    }

    if (data.phValue < 0 || data.phValue > 14) {
      throw mockError(400, 'pH值异常')
    }

    return mockSuccess(null, '环境数据上传成功')
  },

  // 查询环境数据列表
  getEnvironmentDataList: async (params) => {
    await delay(1000)

    const count = random.number(5, 20)
    const data = []

    for (let i = 0; i < count; i++) {
      data.push({
        id: random.number(1, 1000),
        dissolvedOxygen: random.float(6, 12, 2),
        waterTemperature: random.float(15, 35, 2),
        phValue: random.float(6.5, 8.5, 2),
        samplingTime: random.date().getTime(),
        netCageId: params.netCageId || random.number(1, 10)
      })
    }

    return mockSuccess(data)
  },

  // 效益评估计算
  calculateBenefit: async (params) => {
    await delay(1200)

    const count = random.number(3, 8)
    const data = []

    for (let i = 0; i < count; i++) {
      data.push({
        id: random.number(1, 100),
        feedCost: random.float(10, 100, 2),
        laborCost: random.float(5, 50, 2),
        seedlingCost: random.float(50, 200, 2),
        timePeriod: random.number(30, 365),
        netCageId: params.netCageId || random.number(1, 10)
      })
    }

    return mockSuccess(data)
  }
}

// 智慧识鱼相关Mock数据
export const fishRecognitionMock = {
  // 获取最新识别记录
  getRecentRecords: async () => {
    await delay(800)

    const fishNames = ['大黄鱼', '小丑鱼', '鲤鱼', '草鱼', '鲢鱼', '鳙鱼', '青鱼', '鲫鱼']
    const data = []

    for (let i = 0; i < 5; i++) {
      data.push({
        username: `用户${random.choice(['A', 'B', 'C', 'D', 'E'])}`,
        uploadTime: random.date().toLocaleString(),
        fishName: random.choice(fishNames),
        confidence: random.float(0.8, 0.99, 3),
        thumbnail: `/images/thumbnail_${String(i + 1).padStart(3, '0')}.jpg`
      })
    }

    return mockSuccess(data)
  },

  // 获取使用统计
  getStatistics: async () => {
    await delay(600)

    return mockSuccess({
      onlineUsers: random.number(100, 500),
      todayRecognitions: random.number(1000, 3000),
      totalRecognitions: random.number(50000, 200000),
      totalImages: random.number(30000, 150000)
    })
  },

  // 获取最热搜索排行
  getHotRanking: async () => {
    await delay(700)
    const fishNames = ['大黄鱼', '小丑鱼', '鲤鱼', '草鱼', '鲢鱼', '鳙鱼', '青鱼', '鲫鱼', '鲈鱼', '鲑鱼']
    const data = []

    for (let i = 0; i < 10; i++) {
      data.push({
        fishName: fishNames[i],
        searchCount: random.number(500, 5000),
        popularity: random.number(5000, 20000)
      })
    }

    // 按搜索次数排序
    data.sort((a, b) => b.searchCount - a.searchCount)

    return mockSuccess(data)
  },

  // 获取鱼类画像
  getFishProfiles: async () => {
    await delay(1000)

    const profiles = [
      {
        fishName: '大黄鱼',
        scientificName: 'Larimichthys crocea',
        description: '石首鱼科黄鱼属鱼类，体延长，侧扁，头大而钝圆，吻短钝，口大，下颌稍突出。',
        habitat: '西北太平洋区，中国沿海均有分布，主要栖息于水深20-80米的海域。',
        characteristic: '体侧上半部为黄褐色，下半部为银白色，背鳍和尾鳍为黄色，胸鳍和腹鳍为白色。',
        images: ['/images/fish/001-main.jpg', '/images/fish/001-detail.jpg'],
        video: '/videos/fish/001.mp4'
      },
      {
        fishName: '小丑鱼',
        scientificName: 'Amphiprioninae',
        description: '海葵鱼亚科鱼类，体型小巧，色彩鲜艳，与海葵共生。',
        habitat: '热带海洋，主要分布在印度洋和太平洋的珊瑚礁区域。',
        characteristic: '体色鲜艳，通常为橙色或红色，身上有白色条纹，性格温和。',
        images: ['/images/fish/002-main.jpg', '/images/fish/002-detail.jpg'],
        video: '/videos/fish/002.mp4'
      },
      {
        fishName: '鲤鱼',
        scientificName: 'Cyprinus carpio',
        description: '鲤科鲤属鱼类，体延长，侧扁，头较小，口下位，有须。',
        habitat: '淡水鱼类，广泛分布于中国各地，适应性强。',
        characteristic: '体色多样，有青灰色、金黄色等，鳞片较大，尾鳍分叉。',
        images: ['/images/fish/003-main.jpg', '/images/fish/003-detail.jpg'],
        video: '/videos/fish/003.mp4'
      }
    ]

    return mockSuccess(profiles)
  }
}

// 鱼病智慧诊断相关Mock数据
export const fishDiseaseMock = {
  // 健康状态评估
  healthCheck: async (data) => {
    await delay(1000)

    // 模拟健康状态判断逻辑
    let healthStatus = 'Healthy'
    let msg = '网箱健康状态良好'

    if (data.dissolvedOxygen < 5 || data.dissolvedOxygen > 12) {
      healthStatus = 'Unhealthy'
      msg = '溶解氧异常，需要关注'
    }

    if (data.waterTemperature < 10 || data.waterTemperature > 35) {
      healthStatus = 'Unhealthy'
      msg = '水温异常，需要调节'
    }

    if (data.phValue < 6.5 || data.phValue > 8.5) {
      healthStatus = 'Unhealthy'
      msg = 'pH值异常，需要调节'
    }

    return {
      code: 0,
      msg,
      healthStatus
    }
  },

  // 获取专家列表
  getExpertList: async () => {
    await delay(800)

    const experts = [
      {
        id: 1,
        expertName: '张教授',
        title: '教授',
        organization: '中国海洋大学',
        specialtyFish: '海水鱼类',
        specialtyDisease: '病毒性疾病',
        url: '4e5b3aa6-374a-40d6-a9c5-a00c503e60cc.jpg'
      },
      {
        id: 2,
        expertName: '李博士',
        title: '博士',
        organization: '中国科学院海洋研究所',
        specialtyFish: '淡水鱼类',
        specialtyDisease: '细菌性疾病',
        url: '/images/experts/expert2.jpg'
      },
      {
        id: 3,
        expertName: '王研究员',
        title: '研究员',
        organization: '中国水产科学研究院',
        specialtyFish: '观赏鱼类',
        specialtyDisease: '寄生虫病',
        url: '/images/experts/expert3.jpg'
      }
    ]

    return mockSuccess(experts)
  },

  // 获取鱼病识别记录
  getDiseaseList: async () => {
    await delay(900)

    const diseases = ['白点病', '烂鳃病', '肠炎病', '水霉病', '锚头蚤病']
    const fishNames = ['鲤鱼', '草鱼', '鲢鱼', '鳙鱼', '青鱼']
    const data = []

    for (let i = 0; i < 10; i++) {
      data.push({
        id: random.number(1, 1000),
        fishName: random.choice(fishNames),
        netCageId: random.number(1, 10),
        time: random.date().getTime(),
        fishDisease: random.choice(diseases),
        confidence: random.number(70, 95)
      })
    }

    return mockSuccess(data)
  }
}

// Mock WebSocket客户端
export class MockWebSocketClient {
  constructor(url) {
    this.url = url
    this.ws = null
    this.isConnected = false
    this.onMessage = null
    this.interval = null
  }

  connect() {
    console.log('Mock WebSocket连接成功')
    this.isConnected = true

    // 模拟定期发送统计数据
    this.interval = setInterval(() => {
      if (this.isConnected && this.onMessage) {
        const mockData = {
          code: 200,
          data: {
            onlineUsers: random.number(100, 500),
            todayRecognitions: random.number(1000, 3000),
            totalRecognitions: random.number(50000, 200000),
            totalImages: random.number(30000, 150000)
          }
        }
        this.onMessage(mockData)
      }
    }, 3000) // 每3秒发送一次数据
  }

  disconnect() {
    console.log('Mock WebSocket连接断开')
    this.isConnected = false
    if (this.interval) {
      clearInterval(this.interval)
      this.interval = null
    }
  }

  send(data) {
    console.log('Mock WebSocket发送消息:', data)
  }
}

// 创建Mock WebSocket实例
export const mockStatisticsWebSocket = new MockWebSocketClient('wss://4b527230k9.zicp.fun/ws/statistics')
